//
//  M_IndexPageVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/10.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD
import WebKit

class M_IndexPageVC: BaseViewControllerWithHeader,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler {
    
    let mainWeb = WKWebView()
    let logoMallImageView = UIImageView()
    let logoAppImageView = UIImageView()
    var canGo : Bool=true
    
    lazy var defultView : UIView = {
        let v = UIView()
        v.backgroundColor = .clear
        mainWeb.drawView(view: v) { (make) in
            make.left.top.equalToSuperview()
            make.height.width.equalToSuperview()
        }
        let img = v.drawImage(named: "zhaobudaoyemian_114") { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-80)
            make.height.width.equalTo(200)
        }
        img.contentMode = .scaleAspectFit
        
        v.drawLabel(text: "找不到页面", fontSize: 19, textColor: .x333333) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(img.snp.bottom).offset(10)
        }.textAlignment = .center
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        reloadData()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            MBProgressHUD.showOrIncrease(view: self.mainWeb)
        }
        
//        let name1 = NSNotification.Name(rawValue:MALL_CHANGE)
//        NotificationCenter.default.addObserver(self, selector: #selector(notfifica(sender:)), name: name1, object: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        canGo = true
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func getAllSysenterprise(callback: @escaping (Bool,[[String:Any?]]) -> Void) {
        API.formRequest(url: .YI_GetAllSysenterprise, params: nil, callback: { (result) in
            if result.success {
                if let dl = result.data?.getDictList("data") {
                    callback(result.success, dl)
                }
                else {
                    callback(false, [])
                }
            }
            else {
                callback(false, [])
            }
        })
    }
    
    func getSyssettingbase(callback: @escaping (Bool,[String:Any?]) -> Void) {
        API.formRequest(url: .YI_GetSyssettingbase, params: nil, callback: { (result) in
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    callback(result.success, dl)
                }
                else {
                    callback(result.success, [:])
                }
            }
        })
    }
    
    func getSysenterprise(id: String) {
        API.formRequest(url: .YI_GetSysenterpriseById, params: ["mallID":id]) { (result) in
            if result.success {
                if let d = result.data {
                    if let mailLogoUrlString = d.getDictionary("data")?.getString("logo") {
                        self.logoMallImageView.contentMode = .scaleAspectFit
                        self.logoMallImageView.sd_setImage(with: URL(string: mailLogoUrlString))

                    }
                }
                else {
                    
                }
            }
        }
    }
}

// MARK:- UI
extension M_IndexPageVC {
    func setupUI() {
//        headView.backgroundColor = .blue
        headView.snp.remakeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(safeView.snp.top).offset(100-20)
            make.top.equalToSuperview().offset(-44)
        }
        backButton.isHidden = true
        headView.drawButton(imageNamed: "saoyisao_1") { (make) in
            make.left.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-46)
        }
        .addTarget(self, action: #selector(onQRCodeAction(button:)), for: .touchUpInside)
        
        headView.drawImage(imageView: logoAppImageView, image: UIImage(named: "lepaidui_2")) { (make) in
              make.centerX.equalToSuperview()
              make.bottom.equalToSuperview().offset(-43)
        }

        
//        logoMallImageView.backgroundColor = .red
        headView.drawImage(imageView: logoMallImageView, image: nil) { (make) in
            make.centerY.equalTo(logoAppImageView)
            make.left.equalToSuperview().offset(38)
            make.width.equalTo(104)
            make.height.equalTo(26)

        }
        headView.drawButton(imageNamed: "xiangqingkefu_82"){ (make) in
          make.right.equalToSuperview().offset(-10)
          make.bottom.equalToSuperview().offset(-46)
        }
        .addTarget(self, action: #selector(onServiceAction(button:)), for: .touchUpInside)
        
        let newsButton = headView.drawButton(imageNamed: "xiaoxi_4"){ (make) in
          make.right.equalToSuperview().offset(-49)
          make.bottom.equalToSuperview().offset(-46)
        }
        newsButton.addTarget(self, action: #selector(onNewsAction(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                              pointOffset: .init(x: -0.5, y: 1),  color: .xE0551B)
        
        //        背景view
        let search_bgView = headView.drawView() { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-7)
            make.height.equalTo(28)
        }
        search_bgView.backgroundColor = .xF2F2F2
        search_bgView.layer.cornerRadius = 5.0
        
        let field = headView.drawTextField(placeholder: "", fontSize: 12) { (make) in
            make.left.equalTo(search_bgView.snp.left).offset(41)
            make.right.equalTo(search_bgView.snp.right).offset(-10)
            make.centerY.equalTo(search_bgView.snp.centerY)
        }
        field.isEnabled = false
        getSyssettingbase(callback: { (sec,data) in
            if sec {
                field.placeholder = data.getString("proprietarySearchKeyword")
            }
            else {
                field.placeholder = "搜索您想要的商品"
            }
        })
        
        let searchBtn = headView.drawButton(imageNamed: "shousu_5") { (make) in
            make.left.equalTo(search_bgView.snp.left).offset(11)
            make.bottom.equalTo(search_bgView.snp.bottom).offset(-7)
        }
        searchBtn.hitEdgInsets = .init(top: -10, left: -20, bottom: -10, right: -200)
        searchBtn.addTarget(self, action: #selector(onSearchAction(button:)), for: .touchUpInside)
        
        safeView.drawView(view: mainWeb) { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        mainWeb.uiDelegate = self
        mainWeb.navigationDelegate = self
        mainWeb.scrollView.showsVerticalScrollIndicator = false
        mainWeb.scrollView.showsHorizontalScrollIndicator = false
        //禁止长按,放缩
        var javascript = "document.documentElement.style.webkitTouchCallout='none';"//禁止长按
        javascript += "document.documentElement.style.webkitUserSelect='none';"//禁止选择
        var noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
        mainWeb.configuration.userContentController.addUserScript(noneSelectScript)
        javascript = "var script = document.createElement('meta');script.name = 'viewport';script.content=\"width=device-width, user-scalable=no\";document.getElementsByTagName('head')[0].appendChild(script);"//禁止缩放
        noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
        mainWeb.configuration.userContentController.addUserScript(noneSelectScript)
    }
}

// MARK:- 事件
extension M_IndexPageVC {
    func reloadData() {
        deleteWebCache()
        let dic1 = LocalStorage.getDic(forKey: DEFULT_MALL)

        getAllSysenterprise(callback: { (sec,data) in
            if sec {
                self.defultView.isHidden = true
                if let dic = data.first(where: {$0.getString("mallID") == dic1?.getString("mallID")}) {
                    self.loadUrl(INDEX_URL+(anyToString(dic["id"] ?? "") ?? ""))
                }
            }
            else {
                MBProgressHUD.hideOrDecrease()
                self.defultView.isHidden = false
            }
        })
        
        getSysenterprise(id: (dic1?.getString("mallID"))!)
    }
    
    func deleteWebCache() {
    //allWebsiteDataTypes清除所有缓存
        let websiteDataTypes = WKWebsiteDataStore.allWebsiteDataTypes()

        let dateFrom = Date.init(timeIntervalSince1970: 0)
        WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: dateFrom, completionHandler: {
            
        })
    }
    
    func loadUrl(_ url : String) {
        print(url)
        let mapwayURL = URL(string: url+"&action=main")!
        let mapwayRequest = URLRequest(url: mapwayURL)
        mainWeb.load(mapwayRequest)
    }

    @objc func notfifica(sender:NSNotification) {
        reloadData()
    }
    
    ///扫描二维码
    @objc func onQRCodeAction(button:UIButton){
        let scanQRCodeVC = ScaningViewController()
        AppAuthority.cameraPermissions(authorizedBlock: {
            self.pushViewController(scanQRCodeVC)
        }, deniedBlock: {
            
        })
    }
    
    @objc func onServiceAction(button:UIButton){
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        let qidiandic = LocalStorage.getDic(forKey: QIDIAN_KEY)
        vc.loadUrl(qidiandic?.getString("id") ?? "https://url.cn/50hfdES?_type=wpa&qidian=true")
        
        vc.headTitle.text = "联系客服"
    }
    
    @objc func onNewsAction(button:UIButton){
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func onSearchAction(button:UIButton){
        let vc = M_SearchPageVC()
        pushViewController(vc)
    }
    
    ///webkitDelegate_JS
        func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
            // 在JS端调用alert函数时，会触发此代理方法。
            // JS端调用alert时所传的数据可以通过message拿到
            // 在原生得到结果后，需要回调JS，是通过completionHandler回调
        }

        func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
            // JS端调用confirm函数时，会触发此方法
            // 通过message可以拿到JS端所传的数据
            // 在iOS端显示原生alert得到YES/NO后
            // 通过completionHandler回调给JS端
        }

        func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
            // JS端调用prompt函数时，会触发此方法
            // 要求输入一段文本
            // 在原生输入得到文本内容后，通过completionHandler回调给JS
        }

        ///MARK:-WKNavigationDelegate
        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
            //页面开始加载，可在这里给用户loading提示
            defultView.isHidden = true
        }

        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
            //内容开始到达时
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            //页面加载完成时
//            let javascript = "var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"
//             webView.evaluateJavaScript(javascript, completionHandler: nil)
            
            MBProgressHUD.hideOrDecrease()
        }

        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            //页面加载出错，可在这里给用户错误提示
            MBProgressHUD.hideOrDecrease()
            defultView.isHidden = false
        }
        
        func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
            MBProgressHUD.hideOrDecrease()
            defultView.isHidden = false
        }

        func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
            //收到服务器重定向请求
        }

        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            if !canGo {
                decisionHandler(.cancel)
                return
            }
            // 在请求开始加载之前调用，决定是否跳转
            let url = navigationAction.request.url
            print("url:\(String(describing: url?.scheme)), host:\(String(describing: url?.host)), path:\(String(describing: url?.path)), query:\(String(describing: url?.query))")
            if let query = url?.query?.urlqueryToDictionary() {
                print("截取的参数:" + query.jsonString)
                if query.getString("action") == "newProduct",let productNo = query.getString("productNo") {
                    let vc = M_ProductDetailVC(info: ["productNo":productNo])
                    pushViewController(vc)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "slideshowSub",let id = query.getString("special") {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    let url = SPLICE_URL + id
                    vc.loadUrl(url)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "slideshowSub",let id = query.getString("id"),let division = query.getString("division") {
                    let ary = [["cataID":id, "cataName":""]]
                    let vc = M_ProductByCategoryVC(dataSubArr: ary, curDicIndex: 0,zoneCode: .init(fromDictionary: ["code":division,"name":"","sort":0]))
                    pushViewController(vc)
                    vc.tabHeaderHide = true
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "special",let id = query.getString("id"),let division = query.getString("division") {
                    let ary = [["cataID":id, "cataName":""]]
                    let vc = M_ProductByCategoryVC(dataSubArr: ary, curDicIndex: 0,zoneCode: .init(fromDictionary: ["code":division,"name":"","sort":0]))
                    pushViewController(vc)
                    vc.tabHeaderHide = true
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "party",let id = query.getString("article") {
                    let vc = M_HuodongArticleVC()
                    pushViewController(vc)
                    vc.headTitle.text = "活动推文"
                    vc.artId = "\(id)"
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "party",query.getString("more") == "more" {
                    canGo = false
                    let noT = NSNotification.Name(rawValue: GOTOHONME)
                    let dic = ["selIndex":2]
                    NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "special",let id = query.getString("special") {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    let url = SPLICE_URL + id
                    vc.loadUrl(url)
                    canGo = false
                    decisionHandler(.cancel)
                } else if query.getString("action") == "autotrophy",let id = query.getString("special") {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    let url = SPLICE_URL + id
                    vc.loadUrl(url)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "autotrophy",let productNo = query.getString("productNo") {
                    let vc = M_ProductDetailVC(info: ["productNo":productNo])
                    pushViewController(vc)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "jingdong",let productNo = query.getString("goodsID") {
                    let vc = M_ProductDetailVC(info: ["productNo":productNo])
                    pushViewController(vc)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "jingdong",let id = query.getString("special") {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    let url = SPLICE_URL + id
                    vc.loadUrl(url)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "jingdong",let productNo = query.getString("productNo") {
                    let vc = M_ProductDetailVC(info: ["productNo":productNo])
                    pushViewController(vc)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "addToshopingCart",let productNo = query.getString("productNo") {
                    canGo = true
                    addCar(productNo: productNo)
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "main" {
                    decisionHandler(.allow)
                }
                else if query.getString("action") == "Advertisement", let special = query.getString("special")  {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    let url = SPLICE_URL + special
                    vc.loadUrl(url)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "Advertisement", let url = query.getString("url")  {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    vc.loadUrl(url)
                    canGo = false
                    decisionHandler(.cancel)
                }
                else if query.getString("action") == "recommend", let productNo = query.getString("productNo")  {
                    let vc = M_ProductDetailVC(info: ["productNo":productNo])
                    pushViewController(vc)
                    canGo = false
                    decisionHandler(.cancel)
                }
                    
                    
                else {
                    decisionHandler(.cancel)
                }
            }
            else {
                decisionHandler(.allow)
                return
            }
        }

        func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
            //在收到响应开始加载后，决定是否跳转
            decisionHandler(.allow)
        }

        //MARK:-WKScriptMessageHandler
        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            //h5给端传值的内容，可在这里实现h5与原生的交互时间
            let messageDic = message.body
            print(messageDic)

        }
    
    func addCar(productNo: String) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":productNo]
        API.request(url: .M_AddCart, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                let popup = PopupBox(infoText: "成功加入购物车")
                popup.show(vc: UIViewController.topMostController() ?? self)

                let noT = NSNotification.Name(rawValue: CAR_CHANGE)
                let dic = ["key":"value"]
                NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
            }
            else {
                let popup = PopupBox(infoText: result.errMsg ?? "加入购物车失败")
                popup.show(vc: UIViewController.topMostController() ?? self)
            }
        }
    }
}
